package ConveyorBelt.Util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.Properties;

public class ScoreTableLoader {
	public Properties prop;
	public Hashtable<String, String> table;
	public String filePath;
	
	public ScoreTableLoader(String filePath) throws IOException {
		prop = new Properties();
		prop.load(new FileInputStream(filePath));
		this.filePath = filePath;
		table = new Hashtable<String, String> ();
		
		for(Object obj : prop.keySet()) {
			String name = obj.toString();
			String score = prop.getProperty(name);
			table.put(name, score);
		}
	}
	
	public ArrayList<ScoreRecord> loadScoreTable(String filePath) {
		ArrayList<ScoreRecord> srs = new ArrayList<ScoreRecord>();
		for(String key : table.keySet()) {
			String name = key;
			Integer score = new Integer(table.get(key));
			srs.add(new ScoreRecord(name, score));
		}
		Collections.sort(srs);
		return srs;
	}
	
	public boolean saveScoreTable(ArrayList<ScoreRecord> srs) throws FileNotFoundException, IOException {
		boolean saved = true;
		if(srs == null) saved = false;
		else {
			for (int i = 0; i < srs.size(); i++) {
				prop.put(srs.get(i).getName(), String.valueOf(srs.get(i).getScore()));
			}
			prop.store(new FileOutputStream(filePath), null);
		}
		return saved;
	}
}
